<template>
	<view class="page">
		<!-- 顶部统计：课程数 / 已完成 / 学分 -->
		<view class="stats">
			<view class="stats-row">
				<view class="stats-col">
					<view class="num">{{ totalCount }}</view>
					<view class="label">课程数</view>
				</view>
				<view class="stats-col center">
					<view class="num big">{{ doneCount }}</view>
					<view class="label">已完成</view>
				</view>
				<view class="stats-col">
					<view class="num">{{ totalCredits }}</view>
					<view class="label">累计学分</view>
				</view>
			</view>

			<!-- Tabs（只作为导航；仍用它的切换与样式） -->
			<view class="tabs-wrap">
				<wd-tabs :modelValue="activeTab" @update:modelValue="onTabChange" color="#2e7d32"
					inactive-color="#999999" lineWidth="40">
					<block v-for="t in tabs" :key="t.name">
						<wd-tab :name="t.name" :title="t.title">
							<!-- 面板内容不在这里渲染，避免整页滚动 -->
							<view style="display:none;" />
						</wd-tab>
					</block>
				</wd-tabs>
			</view>
		</view>
		<!-- ✅ 只有这个区域滚动 + 左右滑 -->
		<view class="list-area">
			<swiper class="swiper" :current="activeIndex" @change="onSwiperChange"
				:style="{ height: swiperHeight + 'px' }">
				<swiper-item v-for="t in tabs" :key="t.name">
					<scroll-view scroll-y class="list-scroll" :style="{ height: swiperHeight + 'px' }">
						<view class="content">
							<view class="record-list">
								<!-- 包一层相对定位容器，用于放右上角角标 -->
								<view class="card-wrap" v-for="(c, idx) in coursesFor(t.name)" :key="courseKey(c, idx)">
									<!-- 右上角角标 -->
									<view class="corner-tag" :class="isFinished(c) ? 'done' : 'doing'">
										{{ isFinished(c) ? '已完成' : '进行中' }}
									</view>

									<wd-card class="record-card course-card" :use-footer-slot="false">
										<!-- 标题：名称 + 状态（保留。如果只想要右上角角标，可删掉这个 wd-tag） -->
										<template #title>
											<view class="card-title">
												<text class="date name">{{ c.name || c.alias }}</text>
												<wd-tag :type="isFinished(c) ? 'success' : 'warning'" plain
													size="small">
													{{ isFinished(c) ? '已完成' : '进行中' }}
												</wd-tag>
											</view>
										</template>

										<!-- 主体：两行指标 + 进度条 -->
										<template #default>
											<view class="card-body">
												<view class="row kpi">
													<view class="col">
														<text class="label">达标步数：</text>
														<text class="val">{{ fmt(c.targetSteps) }}</text>
														<text class="u">步</text>
													</view>
													<view class="col">
														<text class="label">当前进度：</text>
														<text class="val">{{ fmt(currSteps(c)) }}</text>
														<text class="u">步</text>
													</view>
												</view>

												<view class="row kpi">
													<view class="col">
														<text class="label">截止日期：</text>
														<text class="val">{{ deadline(c) }}</text>
													</view>
													<view class="col">
														<text class="label">目标学分：</text>
														<text class="val">{{ c.credit ?? 0 }}</text>
													</view>
												</view>

												<view class="row progress">
													<wd-progress class="pure-progress" :percentage="percent(c)"
														:show-text="false" :stroke-width="10" />
												</view>
											</view>
										</template>
									</wd-card>
								</view>

								<wd-divider v-if="loading">加载中...</wd-divider>
								<wd-divider v-else-if="!coursesFor(t.name).length">暂无课程</wd-divider>
							</view>
						</view>
					</scroll-view>
				</swiper-item>
			</swiper>
		</view>
	</view>
</template>

<script setup>
	import {
		computed,
		ref,
		onMounted,
		nextTick
	} from 'vue'
	import {
		useAppStore
	} from '@/stores/app'
	import {
		onShow,
		onPullDownRefresh
	} from '@dcloudio/uni-app'

	const store = useAppStore()

	/* ===== 顶部统计 ===== */
	const allCourses = computed(() => store.courses || [])
	const totalCount = computed(() => allCourses.value.length)
	const doneCount = computed(() => allCourses.value.filter(isFinished).length)
	/** 只统计“已完成”课程的学分 */
	const totalCredits = computed(() =>
		allCourses.value.filter(isFinished).reduce((s, c) => s + Number(c.credit || 0), 0)
	)

	/* ===== Tabs ===== */
	const tabs = ref([{
			name: 'all',
			title: '全部'
		},
		{
			name: 'doing',
			title: '进行中'
		},
		{
			name: 'done',
			title: '已完成'
		}
	])
	const activeTab = ref('all')

	function onTabChange(v) {
		activeTab.value = v
	}

	/* 同步 swiper 下标 <-> tab 名称 */
	const name2index = computed(() => {
		const m = {}
		tabs.value.forEach((t, i) => (m[t.name] = i))
		return m
	})
	const activeIndex = computed({
		get() {
			return name2index.value[activeTab.value] ?? 0
		},
		set(i) {
			const t = tabs.value[i];
			if (t) activeTab.value = t.name
		}
	})

	function onSwiperChange(e) {
		activeIndex.value = e.detail.current
	}

	/* ===== 课程计算（仅课程自己的 completedSteps） ===== */
	function currSteps(c) {
		return Number(c.completedSteps || 0)
	}

	function percent(c) {
		const t = Number(c.targetSteps || 0) || 1
		return Math.min(100, Math.round((currSteps(c) / t) * 100))
	}

	function isFinished(c) {
		return currSteps(c) >= (Number(c.targetSteps || 0) || 1)
	}

	function deadline(c) {
		return c.deadline ? String(c.deadline).replace(/-/g, '.') : '-'
	}

	function fmt(n) {
		return (Number(n) || 0).toLocaleString('zh-CN')
	}

	/* 列表：按 Tab 过滤，按截止日期升序 */
	const loading = computed(() => !!store.coursesLoading)

	function coursesFor(tab) {
		let arr = allCourses.value.slice()
		if (tab === 'doing') arr = arr.filter(c => !isFinished(c))
		if (tab === 'done') arr = arr.filter(c => isFinished(c))
		return arr.sort((a, b) => {
			const da = new Date(String(a.deadline || '2099-12-31').replace(/-/g, '/')).getTime()
			const db = new Date(String(b.deadline || '2099-12-31').replace(/-/g, '/')).getTime()
			return da - db
		})
	}
	/* 唯一 key（避免 wx:key 重复） */
	function courseKey(c, idx) {
		return c?.id ? `${c.id}-${idx}` : `idx-${idx}`
	}

	/* ===== 计算下半区高度（窗口高度 - 顶部统计 - tabs 高度） ===== */
	const swiperHeight = ref(0)

	function calcHeights() {
		const wh = uni.getSystemInfoSync().windowHeight
		const query = uni.createSelectorQuery()
		query.select('.stats').boundingClientRect()
		query.select('.tabs-wrap').boundingClientRect()
		query.exec(res => {
			const statsH = res?.[0]?.height || 0
			const tabsH = res?.[1]?.height || 0
			swiperHeight.value = Math.max(0, wh - statsH - tabsH)
		})
	}
	onMounted(() => nextTick(calcHeights))
	onShow(() => nextTick(calcHeights))

	/* 进入页面拉课程；下拉刷新强制拉取（后端负责步数累加与返回） */
	onShow(() => {
		store.fetchCourses()
	})
	onPullDownRefresh(async () => {
		await store.fetchCourses({
			force: true
		})
		uni.stopPullDownRefresh()
		uni.showToast({
			title: '已刷新',
			icon: 'none'
		})
	})
</script>

<style scoped>
	/* ✅ 整页 flex：上不动，下滚动 */
	.page {
		height: 100vh;
		display: flex;
		flex-direction: column;
		background: linear-gradient(to bottom, #c4ffd5 0%, #f5f5f5 35%, #f5f5f5 100%);
	}

	/* 顶部统计（不滚动） */
	.stats {
		padding: 60rpx 30rpx 20rpx;
	}

	.stats-row {
		display: flex;
		justify-content: space-between;
		align-items: flex-start;
	}

	.stats-col {
		flex: 1;
		text-align: center;
	}

	.stats-col.center {
		flex: 1.5;
	}

	.num {
		font-size: 36rpx;
		font-weight: 600;
		color: #000;
		line-height: 1.2;
	}

	.num.big {
		font-size: 56rpx;
		font-weight: 700;
	}

	.label {
		margin-top: 10rpx;
		font-size: 24rpx;
		color: #333;
	}

	/* Tabs 导航（不滚动） */
	.tabs-wrap {
		margin-top: 30rpx;
		background-color: transparent;
		margin-left: 0rpx;
	}

	:deep(.wd-tabs),
	:deep(.wd-tabs__wrap),
	:deep(.wd-tabs__scroll),
	:deep(.wd-tabs__nav),
	:deep(.wd-tabs__nav--line),
	:deep(.wd-tabs__scroll-view),
	:deep(.wd-tabs__scroll-inner) {
		background: transparent !important;
		padding-left: 0 !important;
		padding-right: 0 !important;
		margin-left: 0 !important;
		margin-right: 0 !important;
		box-sizing: border-box;
	}

	:deep(.wd-tabs__item) {
		color: #999;
	}

	:deep(.wd-tabs__item.is-active) {
		color: #2e7d32 !important;
	}

	:deep(.wd-tabs__line) {
		background-color: #2e7d32 !important;
		height: 6rpx !important;
		border-radius: 6rpx;
	}

	/* ✅ 下半区（swiper+scroll）只它滚动与滑动 */
	.list-area {
		flex: 1;
		min-height: 0;
	}

	.swiper {
		width: 100%;
	}

	.list-scroll {
		width: 100%;
	}

	/* 列表与卡片 */
	.content {
		padding: 24rpx 30rpx 60rpx;
	}

	.record-list {
		padding: 20rpx 0 40rpx;
	}

	/* 外层包裹用于角标定位 */
	.card-wrap {
		position: relative;
		margin-bottom: 24rpx;
	}

	/* 卡片本体（去掉 margin-bottom，避免与 .card-wrap 叠加） */
	.record-card.course-card {
		border: 2rpx solid #eaeaea;
		border-radius: 24rpx;
		overflow: hidden;
		margin: 0;
		background: #fff;
		box-shadow: 0 6rpx 18rpx rgba(0, 0, 0, .06);
	}

	/* 右上角“印章”角标 */
	.corner-tag {
		position: absolute;
		top: 5rpx;
		/* 稍微贴边更像盖章，可根据喜好微调 */
		right: 20rpx;
		z-index: 5;
		padding: 6rpx 14rpx;
		font-size: 22rpx;
		line-height: 1;
		border-radius: 999rpx;
		transform: rotate(-12deg);
		box-shadow: 0 4rpx 10rpx rgba(0, 0, 0, .06);
		background: #fff;
		border: 2rpx solid #2e7d32;
		color: #2e7d32;
	}

	.corner-tag.doing {
		border-color: #ff8a00;
		color: #ff8a00;
		background: #fffaf2;
	}

	.corner-tag.done {
		border-color: #2e7d32;
		color: #2e7d32;
		background: #f6fff8;
	}

	:deep(.wd-card__header) {
		padding: 20rpx 22rpx;
	}

	:deep(.wd-card__body) {
		padding: 0 22rpx 12rpx;
	}

	.card-title {
		display: flex;
		align-items: center;
		gap: 12rpx;
	}

	.name {
		font-weight: 700;
	}

	.card-body {
		margin-top: 8rpx;
	}

	.row {
		display: flex;
		align-items: center;
		justify-content: space-between;
		padding: 12rpx 2rpx;
		gap: 12rpx;
	}

	.row.kpi {
		padding-top: 10rpx;
		padding-bottom: 6rpx;
	}

	.col {
		display: flex;
		align-items: baseline;
		gap: 8rpx;
		min-width: 0;
	}

	.label {
		color: #666;
		font-size: 26rpx;
	}

	.val {
		color: #222;
		font-size: 28rpx;
		letter-spacing: 1rpx;
	}

	.u {
		color: #444;
		font-size: 24rpx;
	}

	.row.progress {
		align-items: center;
		padding-top: 8rpx;
	}

	.row.progress :deep(.wd-progress) {
		flex: 1 1 auto;
	}

	/* 隐掉进度条内置文本 */
	.pure-progress ::v-deep(.wd-progress__pivot),
	.pure-progress ::v-deep(.wd-progress__text),
	.pure-progress /deep/ .wd-progress__pivot,
	.pure-progress /deep/ .wd-progress__text,
	.pure-progress>>>.wd-progress__pivot,
	.pure-progress>>>.wd-progress__text,
	.pure-progress ::v-deep(.wd-progress__portion-text) {
		display: none !important;
	}
</style>